package org.kjtc.controller;

import java.io.File;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.kjtc.entity.ChargingRecord;
import org.kjtc.entity.ChargingStationStatus;
import org.kjtc.entity.EquipmentStatus;
import org.kjtc.mongoEntity.Log;
import org.kjtc.mongoService.LogService;
import org.kjtc.service.ChargingRecordService;
import org.kjtc.util.Const;
import org.kjtc.util.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CurveController extends BaseController{
	
	@Resource(name = "logService")
	private LogService logService;

	@Resource(name = "chargingRecordService")
	private ChargingRecordService chargingRecordService;

	@RequestMapping(value = "realTimeCharging")
	@ResponseBody
    public Object getChargingStatus(EquipmentStatus equipmentStatus, String chargingType){

		Map<String, Object> map = new HashMap<String, Object>();
		ChargingStationStatus chargingStationStatus = null;
		Log mongoLog = null;
		List<Log> mongoLogList = null;

		try {
			if ("STATION".equals(chargingType)) {
				List<Object> outputPower = null;
				mongoLog = new Log();
				mongoLog.setMessage("\"chargingStationID\":\"" + equipmentStatus.getChargingStationID());
				if (equipmentStatus.getStartChargingDTTM() != null && !equipmentStatus.getStartChargingDTTM().isEmpty()) {
					mongoLog.setStartTime(equipmentStatus.getStartChargingDTTM());
				} else {
					mongoLog.setStartTime(Tools.date2Str(new Date(), "yyyy-MM-dd"));
				}
				if (equipmentStatus.getEndChargingDTTM() != null && !equipmentStatus.getEndChargingDTTM().isEmpty()) {
					mongoLog.setEndTime(equipmentStatus.getEndChargingDTTM());
				}
				mongoLogList = logService.searchChargingLog(mongoLog);
				mongoLog = null;
				int logLength = mongoLogList.size();
				if (logLength > 0) {
					outputPower = new ArrayList<Object>();
					List<String> tempOutputPower = null;
					for (Log log : mongoLogList) {
						JSONObject messageJson = null;
						if (log.getMessage().indexOf("realTimeData") > 0) {
							messageJson = JSONObject.fromObject(log.getMessage().substring(log.getMessage().indexOf(":") + 1));
						} else {
							messageJson = JSONObject.fromObject(log.getMessage());
						}
						if (messageJson.has("equipmentData")) {
							JSONArray jsonArray = messageJson.getJSONArray("equipmentData");
							int jsonLength = jsonArray.size();
							JSONObject json = null;
							double outputPowerTotal = 0;
							map.put("outputMaxPower", jsonLength * 450);
							for (int j = 0; j < jsonLength; j++) {
								json = jsonArray.getJSONObject(j);
								if (json.has("outputVoltage") && !json.getString("outputVoltage").isEmpty() && json.has("outputElectric") && !json.getString("outputElectric").isEmpty()) {
									outputPowerTotal = outputPowerTotal + (Double.valueOf(json.getString("outputVoltage")) * Double.valueOf(json.getString("outputElectric")) / 1000);
								}
							}
							tempOutputPower = new ArrayList<String>();
							if (messageJson.has("requestDTTM")) {
								tempOutputPower.add(messageJson.getString("requestDTTM"));
							} else {
								tempOutputPower.add(Tools.date2Str(log.getTimestamp()));
							}
							BigDecimal powerTotal = new BigDecimal(outputPowerTotal);
							tempOutputPower.add(String.valueOf(powerTotal.setScale(2, BigDecimal.ROUND_HALF_UP)));
							outputPower.add(tempOutputPower);
							tempOutputPower = null;
						}
					}
				}
				map.put("outputPower", outputPower);
				map.put("result", "Sucess");
				outputPower = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
		}
		chargingStationStatus = null;
		mongoLog = null;
		mongoLogList = null;

		return map;
    }
	
	@RequestMapping(value = "chargingChartHistory")
	@ResponseBody
    public Object getChargingStatus(ChargingRecord chargingRecord){

		Map<String, Object> map = new HashMap<String, Object>();
		Log mongoLog = null;
		List<Log> mongoLogList = null;

		try {
			List<Object> outputVoltage = null;
			List<Object> outputElectric = null;
			List<Object> currentSOC = null;
			mongoLog = new Log();
			String logMessage = null;
			if (chargingRecord.getStartChargingTime() != null && !chargingRecord.getStartChargingTime().isEmpty() && !"-".equals(chargingRecord.getStartChargingTime())) {
				logMessage = "\"startChargingDTTM\":\"" + chargingRecord.getStartChargingTime() + ",";
				if (chargingRecord.getCardNo() != null && !chargingRecord.getCardNo().isEmpty()) {
					logMessage = logMessage + "\"cardNo\":\"" + chargingRecord.getCardNo() + ",";
				}
				if (chargingRecord.getCarNumber() != null && !chargingRecord.getCarNumber().isEmpty()) {
					logMessage = logMessage + "\"carNumber\":\"" + chargingRecord.getCarNumber() + ",";
				}
				logMessage = logMessage + "\"equipmentID\":\"" + chargingRecord.getEquipmentNo();
				mongoLog.setMessage(logMessage);
				mongoLog.setStartTime(chargingRecord.getStartChargingTime());
				if (chargingRecord.getEndChargingTime() == null || chargingRecord.getEndChargingTime().isEmpty()) {
					mongoLog.setEndTime(Tools.date2Str(new Date()));
				} else {
					mongoLog.setEndTime(Tools.date2Str(new Date(Tools.str2DateTime(chargingRecord.getEndChargingTime()).getTime() + 60000)));
				}
			} else {
				logMessage = "\"cardNo\":\"" + chargingRecord.getCardNo() + ",";
				logMessage = logMessage + "\"carNumber\":\"" + chargingRecord.getCarNumber() + ",";
				logMessage = logMessage + "\"equipmentID\":\"" + chargingRecord.getEquipmentNo();
				mongoLog.setMessage(logMessage);
				if (chargingRecord.getStartChargingDate() != null && !chargingRecord.getStartChargingDate().isEmpty()) {
					mongoLog.setStartTime(chargingRecord.getStartChargingDate());
				} else {
					map.put("result", "Error");
					return map;
				}
				if (chargingRecord.getEndChargingDate() != null && !chargingRecord.getEndChargingDate().isEmpty()) {
					mongoLog.setEndTime(Tools.date2Str(new Date(Tools.str2DateTime(chargingRecord.getEndChargingDate()).getTime() + 360000)));
				} else {
					map.put("result", "Error");
					return map;
				}
			}

			mongoLogList = logService.searchChargingLog(mongoLog);
			mongoLog = null;

			int logLength = mongoLogList.size();
			if (logLength > 0) {
				outputVoltage = new ArrayList<Object>();
				outputElectric = new ArrayList<Object>();
				currentSOC = new ArrayList<Object>();
				List<String> tempOutputVoltage = null;
				List<String> tempOutputElectric = null;
				List<String> tempCurrentSOC = null;
				for (Log log : mongoLogList) {
					JSONObject messageJson = null;
					if (log.getMessage().indexOf("realTimeData") > 0) {
						messageJson = JSONObject.fromObject(log.getMessage().substring(log.getMessage().indexOf(":") + 1));
					} else {
						messageJson = JSONObject.fromObject(log.getMessage());
					}
					if (messageJson.has("equipmentData")) {
						JSONArray jsonArray = messageJson.getJSONArray("equipmentData");
						int jsonLength = jsonArray.size();
						JSONObject json = null;
						for (int j = 0; j < jsonLength; j++) {
							json = jsonArray.getJSONObject(j);
							if (json != null && json.getString("equipmentID").equals(chargingRecord.getEquipmentNo())) {
								tempOutputVoltage = new ArrayList<String>();
								tempOutputVoltage.add(Tools.date2Str(log.getTimestamp()));
								if (json.has("outputVoltage")) {
									tempOutputVoltage.add(json.getString("outputVoltage"));
								} else {
									tempOutputVoltage.add("0");
								}
								outputVoltage.add(tempOutputVoltage);
								tempOutputVoltage = null;

								tempOutputElectric = new ArrayList<String>();
								tempOutputElectric.add(Tools.date2Str(log.getTimestamp()));
								if (json.has("outputElectric")) {
									tempOutputElectric.add(json.getString("outputElectric"));
								} else {
									tempOutputElectric.add("0");
								}
								outputElectric.add(tempOutputElectric);
								tempOutputElectric = null;

								tempCurrentSOC = new ArrayList<String>();
								tempCurrentSOC.add(Tools.date2Str(log.getTimestamp()));
								if (json.has("currentSOC")) {
									tempCurrentSOC.add(json.getString("currentSOC"));
								} else {
									tempCurrentSOC.add("0");
								}
								currentSOC.add(tempCurrentSOC);
								tempCurrentSOC = null;
							}
						}
					}
				}
			}
			map.put("result", "Sucess");
			map.put("outputVoltage", outputVoltage);
			map.put("outputElectric", outputElectric);
			map.put("currentSOC", currentSOC);
			outputVoltage = null;
			outputElectric = null;
			currentSOC = null;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录历史充电曲线信息获取异常:" + e.getMessage());
		}
		return map;
	}
	
	@RequestMapping (value = "/searchChargingRecord")
	@ResponseBody
	public Map<String, Object> searchChargingRecord(ChargingRecord chargingRecord)  {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录详细查询开始");

		List<ChargingRecord> chargingRecordList = null;
		try {
			chargingRecordList = chargingRecordService.getChargingRecord(chargingRecord);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录详细查询异常" + e.getMessage());
			return map;
		}
		map.put("chargingRecordList", chargingRecordList);
		chargingRecord = null;
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录详细查询结束");
		return map;
	}
}
